package cn.wu.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import cn.wu.reggie.common.R;
import cn.wu.reggie.entity.User;
import cn.wu.reggie.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session){

        // 生成验证码
        String code = RandomUtil.randomNumbers(4);
        System.out.println("code = " + code);

        // 放入session中
        session.setAttribute(user.getPhone(),code);
        return R.success(null);
    }

    @PostMapping("login")
    public R login(@RequestBody Map<String,String> map,HttpSession session){
        //1.获取用户输入的手机号和验证码
        String requestCode = map.get("code");
        String phone = map.get("phone");

        //2.获取session中验证码
        String sessionCode = (String) session.getAttribute(phone);

        //3.调用service完成登陆注册
        R<User> r = userService.login(phone,requestCode,sessionCode);

        //4.若用户登陆成功,将用户手机号存入session中,把验证码从session中删除
        if (r.getCode()==1) {
            session.setAttribute("user",phone);
            session.removeAttribute(phone);
        }

        return R.success(null);
    }

}
